package com.huatai.datacenter.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.huatai.common.httputil.HttpRequest;
import com.huatai.datacenter.config.ServerInfo;
import com.huatai.datacenter.entity.QueryMultiple;
import com.huatai.datacenter.entity.QueryReturn;
import com.huatai.datacenter.entity.QuerySingle;
import com.huatai.datacenter.entity.datamodel.DataModelEntity;
import com.huatai.datacenter.entity.dataquality.QualityLogEntity;
import com.huatai.datacenter.mapper.DataModelMapper;
import com.huatai.datacenter.mapper.QualityLogMapper;
import com.huatai.datacenter.service.QueryService;
import com.huatai.datacenter.service.ResultErrorHandle;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * @program: ht-system
 * @description: 数据查询
 * @author: songxiude
 * @create: 2023-04-25 15:00
 **/
@Slf4j
@Service
public class QueryServiceImpl extends BaseServiceImpl implements QueryService {

	/**
	 * 大数据服务地址信息
	 */
	@Autowired
	private ServerInfo serverInfo;
	/**
	 * 错误处理
	 */
	@Autowired
	private ResultErrorHandle resultErrorHandle;

	@Autowired
	private QualityLogMapper qualityLogMapper;

	@Autowired
	private DataModelMapper dataModelMapper;



	/**
	 * 保存质量日志并返回新记录的ID
	 * @param
	 * @return 新生成的质量日志ID
	 */
	public String saveQualityLog(Long id) {
		// 1. 查询数据模型名称
		String dataModelName= String.valueOf(getDataModelIdByName(id));

		// 2. 创建并填充实体对象
		QualityLogEntity logEntity = new QualityLogEntity();
		logEntity.setDataModelId(id);
		logEntity.setDataModelName(dataModelName);
		logEntity.setLastExecuteTime(LocalDateTime.now()); // 设置当前时间为上次执行时间
		// 4. 返回新生成的ID
		return logEntity.getDataModelName();
	}

	/**
	 * 根据数据模型名称获取其ID
	 *
	 * @return 数据模型ID
	 */
	private String getDataModelIdByName(Long id) {
		LambdaQueryWrapper<DataModelEntity> wrapper = Wrappers.lambdaQuery();
		wrapper.eq(DataModelEntity::getId, id)
				.select(DataModelEntity::getDataModelName);

		DataModelEntity modelEntity = dataModelMapper.selectOne(wrapper);
		return modelEntity.getDataModelName();
	}

	/**
	 * 基础查询服务
	 */
	@Override
	public List<QueryReturn> query(QuerySingle querySingle) {
		// 获取基础查询url
		String queryUrl = serverInfo.getQueryUrl();
		// 组合为JSON字符串
		String compose = composeQuery(querySingle);
		// 发送请求
		// 错误信息获取
		// 错误查询处理器
		return HttpRequest.post(queryUrl)
			.connectTimeout(Duration.ofSeconds(1000))
			.readTimeout(Duration.ofSeconds(1000))
			.bodyString(compose)
			.execute()
			.onFailed(((request, e) -> {
				log.error("big data query error, info: " + e.getMessage());
				// 错误信息获取
				if (StringUtils.containsAny(e.getMessage(), serverInfo.getErrorMessage())) {
					// 错误查询处理器
					resultErrorHandle.queryInit(querySingle);
				}
			}))
			.onSuccessOpt(responseSpec -> responseSpec.asList(QueryReturn.class))
			.map(this::queryTwoDecimalPlaces)
			.map(response -> writeIsNull(response, querySingle))
			.orElseGet(() -> writeIsNull(new ArrayList<>(), querySingle));
	}

	/**
	 * 多设备查询服务
	 */
	@Override
	public List<QueryReturn> query(QueryMultiple queryMultiple) {
		// 组合为JSON字符串
		String compose = composeQuery(queryMultiple);
		// 获取基础查询url
		String queryUrl = serverInfo.getQueryUrl();
		// 发送请求
		return HttpRequest.post(queryUrl)
			.connectTimeout(Duration.ofSeconds(1000))
			.readTimeout(Duration.ofSeconds(1000))
			.bodyString(compose)
			.execute()
			.onFailed(((request, e) -> {
				log.error("big data query error, info: " + e.getMessage());
				// 错误信息获取
				if (StringUtils.containsAny(e.getMessage(), serverInfo.getErrorMessage())) {
					// 错误查询处理器
					resultErrorHandle.queryInit(queryMultiple);
				}
			}))
			.onSuccessOpt(responseSpec -> responseSpec.asList(QueryReturn.class))
			.map(this::queryTwoDecimalPlaces)
			.map(response -> writeIsNull(response, queryMultiple))
			.orElseGet(() -> writeIsNull(new ArrayList<>(), queryMultiple));
	}

	/**
	 * 获取差值
	 */
	@Override
	public List<QueryReturn> queryDifference(QuerySingle querySingle) {
		// 组合为JSON字符串
		String compose = composeQueryDifference(querySingle);
		// 获取基础查询url
		String queryUrl = serverInfo.getQueryUrl();
		// 发送请求
		// 错误信息获取
		// 错误查询处理器
		return HttpRequest.post(queryUrl)
			.connectTimeout(Duration.ofSeconds(1000))
			.readTimeout(Duration.ofSeconds(1000))
			.bodyString(compose)
			.execute()
			.onFailed(((request, e) -> {
				log.error("big data put error, info: " + e.getMessage());
				// 错误信息获取
				if (StringUtils.containsAny(e.getMessage(), serverInfo.getErrorMessage())) {
					// 错误查询处理器
					resultErrorHandle.queryInit(querySingle);
				}
			}))
			.onSuccessOpt(responseSpec -> responseSpec.asList(QueryReturn.class))
			.map(this::queryTwoDecimalPlaces)
			.map(response -> writeIsNull(response, querySingle))
			.orElseGet(() -> writeIsNull(new ArrayList<>(), querySingle));
	}


}
